package controller;

import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;

@Controller
public class PictureUploadController {

    @RequestMapping(value = "/pictureUpload")
    public String handlePic(@RequestParam("name") String name,
                            @RequestParam("uploadPic") MultipartFile uploadPic,
                            HttpServletRequest request) {
        // 判断所上传文件是否存在
        if (!uploadPic.isEmpty()) {
            //循环输出上传的文件
                // 设置上传文件的保存地址目录
                String dirPath = "S:\\Study\\JavaEEFinalExam2021\\BookManager\\src\\main\\webapp\\images\\books\\";
                File filePath = new File(dirPath);
                // 如果保存文件的地址不存在，就先创建目录
                if (!filePath.exists()) {
                    filePath.mkdirs();
                }
                //上传文件
                try {
                    uploadPic.transferTo(new File(dirPath + name+".jpg"));
                } catch (IOException e) {
                    e.printStackTrace();
                    return "redirect:/BookAll";
                }
        }
        return "redirect:/BookAll";
    }
}
